package com.itheima.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.itheima.entity.dto.PhoneDto;
import com.itheima.entity.pojo.User;
import com.itheima.entity.vo.user.UserVo;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * @author huangzelnag
 * @create 2022-05-12
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;


    @Override
    public UserVo getUser( String phone) {
      //1.查找是否有这个用户存在，有则返回
        UserVo userVo = new UserVo();

         User user =userMapper.selectByPhone(phone);
         if(Objects.nonNull(user)){

             BeanUtils.copyProperties(user, userVo);
             return userVo;
         }

     //2.存入用户表

        User user1 = new User();
        String idStr = new Snowflake().nextIdStr();
        user1.setId(idStr);
        user1.setPhone(phone);
        Boolean insert = userMapper.insert(user1);
        //3.根据id获取用户信息

        User user2 = userMapper.selectById(idStr);
        BeanUtils.copyProperties(user2, userVo);

        return userVo;
    }

    /**
     * 退出登陆
     * @param token
     */
    @Override
    public void logout(String token) {

        token = DigestUtils.md5DigestAsHex(token.getBytes());

        redisTemplate.delete(token);

    }






}
